<template>
  <body class="hold-transition">
  <div id="app" style="width: 85vw;">
    <div class="content-header">
      <h1>功能管理<small>订单管理</small></h1>
      <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>功能管理</el-breadcrumb-item>
        <el-breadcrumb-item>订单管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="app-container">
      <div class="box">
        <div class="filter-container">
          <el-input placeholder="订单号/车次号" v-model="pagination.queryString" style="width: 200px;" class="filter-item"
                    @keyup.enter.native="handleFilter" />
          <el-button @click="findPage" class="dalfBut">查询</el-button>
          <el-button type="primary" class="butT" @click="handleCreate">新建订单</el-button>
        </div>

        <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
          <el-table-column type="index" align="center" label="序号" />
          <el-table-column prop="orderNumber" label="订单号" align="center" />
          <el-table-column prop="dispatchId" label="车次号" align="center" />
          <el-table-column prop="customerName" label="客户姓名" align="center" />
          <el-table-column prop="seatNumber" label="座位号" align="center" />
          <el-table-column prop="price" label="票价" align="center" />
          <el-table-column prop="status" label="状态" align="center" />
          <el-table-column label="操作" align="center" width="240">
            <template #default="scope">
              <el-button type="primary" size="mini" @click="handleReschedule(scope.row)">改签</el-button>
              <el-button size="mini" type="danger" @click="handleRefund(scope.row.orderID)">退票</el-button>
              <el-button size="mini" type="success" @click="handleConfirm(scope.row)">确认</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
              class="pagination"
              @current-change="handlePageChange"
              :current-page="pagination.currentPage"
              :page-size="pagination.pageSize"
              :total="pagination.total"
              layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
        </div>

        <!-- 新增订单/改签弹窗 -->
        <el-dialog title="订单操作" v-model="dialogFormVisible">
          <el-form :model="formData" :rules="formRules" label-position="right" label-width="100px" ref="formRef">
            <el-form-item label="订单号" prop="orderNumber">
              <el-input v-model="formData.orderNumber" disabled />
            </el-form-item>

            <el-form-item label="客户姓名" prop="customerName">
              <el-input v-model="formData.customerName" :disabled="formData.isReschedule" placeholder="请输入客户姓名" />
            </el-form-item>
            <el-form-item label="车次号" prop="dispatchId">
              <el-select v-model="formData.dispatchId" placeholder="请选择车次">
                <el-option v-for="dispatch in dispatchIds" :key="dispatch" :label="dispatch" :value="dispatch" />
              </el-select>
            </el-form-item>
            <el-form-item label="座位号" prop="seatNumber">
              <el-input v-model="formData.seatNumber" placeholder="请输入座位号" />
            </el-form-item>
            <el-form-item label="票价" prop="price">
              <el-input v-model.number="formData.price" :disabled="formData.isReschedule" placeholder="请输入票价" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAdd">确定</el-button>
          </div>
        </el-dialog>

      </div>
    </div>
  </div>
  </body>
</template>

<script>
import { reactive, onMounted, toRefs } from "vue";
import service from "@/util/http"; // 假设已有封装的 HTTP 请求库
import { ElMessage, ElMessageBox } from "element-plus";


export default {
  setup() {

    const data = reactive({
      formRef:{},
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        queryString: "",
      },
      dataList: [], // 订单数据
      formData: {
        customerName: "",
        dispatchId: "",
        seatNumber: "",
        price: "",
      }, // 表单数据
      dialogFormVisible: false, // 控制新增窗口显示
      dispatchIds: [], // 车次列表
      formRules: {
        orderNumber: [{ required: true, message: '订单号不能为空', trigger: 'blur' }],
        customerName: [{ required: true, message: '客户姓名不能为空', trigger: 'blur' }],
        dispatchId: [
          { required: true, message: '请选择车次', trigger: ['change', 'blur'] } // 添加 blur
        ],
        seatNumber: [{ required: true, message: '座位号不能为空', trigger: 'blur' }],
        price: [
          { required: true, message: '票价不能为空', trigger: 'blur' },
          { type: 'number', message: '票价必须为数字', trigger: 'blur' },
        ],
      },
    });

    const fetchDispatchIds = () => {
      service.get("/admin/checi/dispatchIds").then((response) => {
        console.log(response);
        if (response.data) {
          const result = response.data;
          if (result.flag) {
            data.dispatchIds = result.data;
          } else {
            ElMessage.error(result.message || '获取车次号列表失败');
          }
        } else {
          ElMessage.error('获取车次号列表失败');
        }
      }).catch((error) => {
        console.error('请求失败:', error);
        ElMessage.error('获取车次号列表请求失败');
      });
    };

    const findPage = (page = 1) => {
      data.pagination.currentPage = page;
      const params = {
        currentPage: data.pagination.currentPage,
        pageSize: data.pagination.pageSize,
        queryString: data.pagination.queryString,
      };
      service.get("/admin/orders/findPage", { params }).then((response) => {
        const { records, total } = response.data.data;
        console.log("dataList (records):", records); // 打印 dataList 的内容
        data.dataList = records;
        data.pagination.total = total;
      });
    };

    const handleCreate = async () => {
      try {
        const response = await service.get("/admin/orders/generate/orderNumber");
        data.formData = {
          orderNumber: response.data.data, // 从后端获取生成的订单号
          isReschedule: false, // 清除改签标志
        };
        data.dialogFormVisible = true;
      } catch (error) {
        ElMessage.error("订单号生成失败，请稍后再试！");
      }
    };

    const handleAdd = () => {
      const isReschedule = !!data.formData.orderID; // 判断是否为改签
      const apiEndpoint = isReschedule
          ? `/admin/orders/reschedule/${data.formData.orderID}`
          : "/admin/orders/add";
      const method = isReschedule ? "put" : "post";

      data.formRef.validate((valid) => {
        if (valid) {
          service[method](apiEndpoint, data.formData).then((response) => {
            ElMessage.success(response.data.message);
            data.dialogFormVisible = false;
            findPage();
          });
        } else {
          ElMessage.error("操作失败，请检查输入项！");
        }
      });
    };

    const handleConfirm = async (row) => {
      try {
        // 确认操作
        // 获取订单详情，确保数据最新
        const response1 = await service.get(`/admin/orders/${row.orderID}`);
        const order = response1.data.data;

        if (!order) {
          ElMessage.error("订单不存在，请刷新页面后重试！");
          return;
        }

        if (order.status === "Cancelled") {
          ElMessage.warning("已确认的订单不能取消！！");
          return;
        }

        if (order.status === "Completed") {
          ElMessage.warning("订单已确认！");
          return;
        }

        await ElMessageBox.confirm(`确定要确认订单 ${row.orderNumber} 吗？确认后将无法进行改签`, '确认订单', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });

        // 调用确认接口
        const response = await service.put(`/admin/orders/confirm/${row.orderID}`);
        if (response.data.flag) {
          ElMessage.success('订单确认成功！');
          findPage(); // 刷新订单列表
        } else {
          ElMessage.error('订单确认失败：' + response.data.message);
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('确认订单失败:', error);
          ElMessage.error('确认订单失败，请稍后再试！');
        } else {
          ElMessage.info('已取消操作');
        }
      }
    };

    const handleReschedule = async (row) => {
      try {
        // 获取订单详情，确保数据最新
        const response = await service.get(`/admin/orders/${row.orderID}`);
        const order = response.data.data;

        if (!order) {
          ElMessage.error("订单不存在，请刷新页面后重试！");
          return;
        }

        if (order.status === "Cancelled") {
          ElMessage.warning("已取消的订单不能改签！");
          return;
        }

        if (order.status === "Completed") {
          ElMessage.warning("已确认的订单不能改签！");
          return;
        }

        if (order.status === "Pending") {
          // 初始化表单并设置为改签状态
          data.formData = {...order, isReschedule: true};
          data.dialogFormVisible = true;
        }
      } catch (error) {
        console.error("改签初始化失败:", error);
        ElMessage.error("改签失败，请稍后再试！");
      }
    };

    const handleRefund = async (id) => {
      try {
        // 获取订单详情
        const response = await service.get(`/admin/orders/${id}`);
        const order = response.data.data;

        if (!order) {
          ElMessage.error("订单不存在，请刷新页面后重试！");
          return;
        }

        if (order.status === "Cancelled") {
          ElMessage.warning("该订单已取消，无法重复退票！");
          return;
        }

        if (order.status !== "Pending" && order.status !== "Confirmed") {
          ElMessage.warning("只有未完成的订单可以退票！");
          return;
        }

        // 用户确认操作
        await ElMessageBox.confirm("确定要退票吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        // 调用退票接口
        const refundResponse = await service.put(`/admin/orders/refund/${id}`);
        ElMessage.success(refundResponse.data.message);

        // 刷新列表
        findPage();
      } catch (error) {
        if (error !== "cancel") {
          console.error("退票失败:", error);
          ElMessage.error("退票失败，请稍后再试！");
        } else {
          ElMessage.info("已取消操作");
        }
      }
    };

    const handleFilter = async () => {
      data.pagination.currentPage = 1; // 重置为第一页
      const params = {
        currentPage: data.pagination.currentPage,
        pageSize: data.pagination.pageSize,
        queryString: data.pagination.queryString,
      };
      try {
        const { data } = await api.getList(params);
        if (data.flag) {
          dataList.value = data.data.records;
          total.value = data.data.total;
        } else {
          ElMessage.error(data.message);
        }
      } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('查询失败');
      }
    };

    const handlePageChange = (newPage) => {
      data.pagination.currentPage = newPage;
      handleFilter(); // 重新执行查询
    };

    onMounted(() => {
      findPage();
      fetchDispatchIds();
    });

    return { ...toRefs(data), findPage, handleCreate, handleAdd, handleReschedule, handleRefund, handleFilter, handlePageChange, handleConfirm };
  },
};
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>